package com.dingding.activity.core.activity.dao.impl;

import java.util.List;

import javax.annotation.Resource;

import org.apache.log4j.Logger;
import org.springframework.stereotype.Component;

import com.dingding.activity.core.activity.dao.IActivityCacheDao;
import com.dingding.activity.core.activity.dao.IActivityDao;
import com.dingding.common.core.beans.Activity;
import com.dingding.common.core.cache.CacheConstants;
import com.dingding.common.core.cache.base.JedisUtil;
import com.dingding.common.core.cache.enums.DbEnum;
import com.dingding.common.core.util.JSONUtil;

/**
 * 
 * @Description: 活动缓存操作DAO
 * @author CHEHUANBO
 * @date 2016年12月8日
 * @version V2.6.2
 * 
 */
@Component("activityCacheDao")
public class ActivityCacheDaoImpl implements IActivityCacheDao {

	private static final Logger log = Logger.getLogger(ActivityCacheDaoImpl.class);

	/**
	 * 是否初始化缓存
	 */
	private static boolean is_intital = true;

	@Resource(name = "_activityDao")
	private IActivityDao activityDao;

	/**
	 * 
	 * @Description: 从缓存中获取所有的有效活动,并根据优先级排序
	 * @author CHEHUANBO
	 * @date 2016-12-06
	 * @since V2.6.2
	 * @Override 
	 * 
	 */
	public List<Activity> getAllActivityToCache() {

		String cacheKey = CacheConstants.ACTIVITY_LIST;

		// 初始化活动缓存
		if (is_intital) {
			return this.setAllActivityToCache(cacheKey);
		} else {
			String cacheValue = JedisUtil.getValue(cacheKey, DbEnum.ActivityDb.getValue());
			List<Activity> activitieList = JSONUtil.parseArray(cacheValue, Activity.class);
			return activitieList;
		}

	}

	/**
	 * 
	 * @Description: 设置所有有效活动到缓存中,并返回活动集合
	 * @author CHEHUANBO
	 * @version V2.6.2
	 * 
	 */
	public List<Activity> setAllActivityToCache(String key) {

		try {

			// 从数据库中获取所有有效活动
			List<Activity> activitieList = activityDao.getAllActivityToDb();
			// 设计所有有效活动到缓存中
			JedisUtil.setValue(key, JSONUtil.toJSONString(activitieList), DbEnum.ActivityDb.getValue());

			return activitieList;

		} catch (Exception e) {
			log.error("设置所有有效活动到缓存中出现异常！", e);
		}

		return null;

	}

}
